import { getRoutes } from '@/api/sys/menu'
import Layout from '@/layout'
import { constantRoutes } from '@/router/index'

const getDefaultState = () => {
  return {
    routes: [], // 路由
    addRoutes: []
  }
}
const state = getDefaultState()
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}
const actions = {
  createRoute({ commit }) {
    return new Promise((resolve) => {
      getRoutes().then((resp) => {
        const { data } = resp
        const formatMenus = transformData(data)
        console.log('🚀 ~ getRoutes ~ formatMenus:', formatMenus)

        commit('SET_ROUTES', formatMenus)

        resolve(formatMenus)
      })
    })
  }
}

function transformData(menus) {
  return menus.map((menu) => {
    return {
      ...menu,
      path: menu.component == 'Layout' ? `/${menu.path}` : menu.path,
      component: menu.component == 'Layout' ? Layout : (resolve) => require(['@/views' + menu.component], resolve),
      // component: menu.component == 'Layout' ? Layout : require('@/views/' + menu.component).default || require('@/views/' + menu.component),
      children: menu.children ? transformData(menu.children) : null
    }
  })
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
